package patrol.mobile.com.mobilepatrol.activity.monitor;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.activity.office.AdviceDetailActivity;
import patrol.mobile.com.mobilepatrol.adapter.GlideImageLoader;
import patrol.mobile.com.mobilepatrol.adapter.ImagePickerAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.DateBean;
import patrol.mobile.com.mobilepatrol.bean.UpImgInfoBean;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.utils.DatePickerUtil02;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.LuBanHelper;
import patrol.mobile.com.mobilepatrol.utils.TimeUtils;
import patrol.mobile.com.mobilepatrol.utils.ToastUtils;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;
import patrol.mobile.com.mobilepatrol.view.CallBack;
import patrol.mobile.com.mobilepatrol.widget.dialog.SelectDialog;

/**
 * Created by z on 2018/9/20.
 * Des: 维修记录
 */

public class WxjuDetailActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {
    @BindView(R.id.mEditWeixiuren)
    EditText mEditWeixiuren;
    @BindView(R.id.mEditWeixiushijian)
    TextView mEditWeixiushijian;
    @BindView(R.id.mEditWeixiuNeirong)
    EditText mEditWeixiuNeirong;
    @BindView(R.id.mEditWeixiuTianshu)
    EditText mEditWeixiuTianshu;
    @BindView(R.id.commitDataText)
    TextView commitDataText;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
//    @BindView(R.id.weiweihuLayout)
//    LinearLayout weiweihuLayout;
//    @BindView(R.id.weihuzhongLayout)
//    LinearLayout weihuzhongLayout;
//    @BindView(R.id.weihuwanchengLayout)
//    LinearLayout weihuwanchengLayout;
    private static final String ADVICE_ID = "ADVICE_ID";
    @BindView(R.id.weiImage)
    RadioButton weiImage;
    @BindView(R.id.zhongImage)
    RadioButton zhongImage;
    @BindView(R.id.wanchengImage)
    RadioButton wanchengImage;
    @BindView(R.id.tupianxuanzhe)
    TextView tupianxuanzhe;
    private ArrayList<ImageItem> selImageList;
    private List<UpImgInfoBean> oldImgInfo;
    private ImagePickerAdapter adapter;
    private int limitSize = 4;
    private String id;
    private List<String> imgUUIDs = new ArrayList<>();
    private String repairFlag = "1";        // 维修状态 1：未维修  2：维修中 3：维修完成

    // TODO: 2019/1/30 相关照片功能
    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_weixiujilu_layout;
    }

    @Override
    public void initTitle() {
        super.initTitle();
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("维修记录");
        mEditWeixiushijian.setText(TimeUtils.dateString4(System.currentTimeMillis()));
        mEditWeixiuren.setText(UserManager.getryName());
        id = getIntent().getStringExtra("id");
        oldImgInfo = new ArrayList<>();
    }

    @Override
    public void setListener() {
        commitDataText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commit();
            }
        });
        mEditWeixiushijian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerUtil02.getInstance(v.getContext()).setCallBack(new CallBack<DateBean>() {
                    @Override
                    public void onBack(DateBean dateBean) {
                        mEditWeixiushijian.setText(dateBean.getmDate());
                    }
                });
            }
        });

        weiImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                repairFlag = "1";
                setType();
            }
        });
        zhongImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                repairFlag = "2";
                setType();
            }
        });
        wanchengImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                repairFlag = "3";
                setType();
            }
        });

    }

    private void setType() {
        switch (repairFlag) {
            case "3":
                wanchengImage.setChecked(true);
                zhongImage.setChecked(false);
                weiImage.setChecked(false);
//                wanchengImage.setImageResource(R.mipmap.radio_button_on);
//                zhongImage.setImageResource(R.mipmap.radio);
//                weiImage.setImageResource(R.mipmap.radio);
                break;
            case "2":
                wanchengImage.setChecked(false);
                zhongImage.setChecked(true);
                weiImage.setChecked(false);
//                wanchengImage.setImageResource(R.mipmap.radio);
//                zhongImage.setImageResource(R.mipmap.radio_button_on);
//                weiImage.setImageResource(R.mipmap.radio);
                break;
            default:
                wanchengImage.setChecked(false);
                zhongImage.setChecked(false);
                weiImage.setChecked(true);
//                wanchengImage.setImageResource(R.mipmap.radio);
//                zhongImage.setImageResource(R.mipmap.radio);
//                weiImage.setImageResource(R.mipmap.radio_button_on);
                break;
        }
    }

    private void commit() {
        if (TextUtils.isEmpty(mEditWeixiuren.getText())) {
            ToastUtils.showToast("请填写维护人");
            return;
        }
        if (TextUtils.isEmpty(mEditWeixiushijian.getText())) {
            ToastUtils.showToast("请选择维护时间");
            return;
        }
        if (TextUtils.isEmpty(mEditWeixiuTianshu.getText())) {
            ToastUtils.showToast("请填写维护天数");
            return;
        }
        if (TextUtils.isEmpty(mEditWeixiuNeirong.getText())) {
            ToastUtils.showToast("请填写维护内容");
            return;
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("repairor", mEditWeixiuren.getText().toString());
        hashMap.put("date", TimeUtils.timeToData07(mEditWeixiushijian.getText().toString()));
        hashMap.put("days", mEditWeixiuTianshu.getText().toString());
        hashMap.put("repairFlag", repairFlag);
        hashMap.put("repairContext", mEditWeixiuNeirong.getText().toString());
        hashMap.put("id", UserManager.getUserId() + System.currentTimeMillis());
        HashMap<String, Object> elefailrec = new HashMap<>();
        elefailrec.put("id", id);
        elefailrec.put("isNewRecord", false);
        hashMap.put("elefailrec", elefailrec);
        HashMap hashMap1 = new HashMap();
        hashMap1.put("mainJson", new Gson().toJson(hashMap));

        List<ImageItem> images = adapter.getImages();
        List<UpImgInfoBean> upImgInfoBeanList = new ArrayList<>();
        for (ImageItem image : images) {
            UpImgInfoBean imgInfoBean = new UpImgInfoBean();
            imgInfoBean.setBusniessId((String) hashMap.get("id"));
            imgInfoBean.setContentType("jiankkElefailrecDiv");
            imgInfoBean.setFileType("img");
            String uuid = UUID.randomUUID().toString();
            imgUUIDs.add(uuid);
            imgInfoBean.setId(uuid);
            upImgInfoBeanList.add(imgInfoBean);
        }
        hashMap1.put("sysAttachmentsJson", GsonUtil.bean2Json(upImgInfoBeanList));

        HttpSender sender = new HttpSender(this, baseUrl, Urls.jiankkElefailrecDivUploadData);
        sender.requestPost(hashMap1, new HttpCallBack(sender) {

            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                ToastUtils.showToast("文本提交成功");
                upImg();
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        initImagePicker();
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, limitSize);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, limitSize));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(4);              //选中数量限制
        imagePicker.setMultiMode(false);                      //多选
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case AdviceDetailActivity.IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent = new Intent(view.getContext(), ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, AdviceDetailActivity.REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent1 = new Intent(view.getContext(), ImageGridActivity.class);
                                startActivityForResult(intent1, AdviceDetailActivity.REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, AdviceDetailActivity.REQUEST_CODE_PREVIEW);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case ImagePicker.RESULT_CODE_ITEMS:
                    //添加图片返回
                    ArrayList<ImageItem> images;
                    if (requestCode == AdviceDetailActivity.REQUEST_CODE_SELECT) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        if (images != null) {
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case ImagePicker.RESULT_CODE_BACK:
                    //预览图片返回
                    if (requestCode == AdviceDetailActivity.REQUEST_CODE_PREVIEW) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                        if (images != null) {
                            selImageList.clear();
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
            }
        }
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

    private void upImg() {
        if (selImageList != null && selImageList.size() != 0) {
            List<File> list = new ArrayList<>();
            for (ImageItem imageItem : selImageList) {
                File file = new File(imageItem.path);
                list.add(file);
            }
            List<Map<String, String>> params = new ArrayList<>();
            for (String imgUUID : imgUUIDs) {
                Map<String, String> map = new HashMap<>();
                map.put("id", imgUUID);
                map.put("type", "jiankkElefailrecDiv");
                params.add(map);
            }
            LuBanHelper luBanHelper = new LuBanHelper(WxjuDetailActivity.this, list, params);
            luBanHelper.compression(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(String response, int id) {
                    Toast.makeText(WxjuDetailActivity.this, "图片提交成功", Toast.LENGTH_SHORT).show();
                    finish();
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
